package com.cornergj.interfaces.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.Oauth;
import weibo4j.model.WeiboException;

import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.cornergj.model.Entity.CommonUserCriteria;
import com.cornergj.model.Entity.FrontImgCriteria;
import com.cornergj.model.Entity.Pagination;
import com.cornergj.model.Entity.SiteOfProvinceCriteria;
import com.cornergj.model.Entity.ThirdAuthorizeUserCriteria;
import com.cornergj.model.Entity.UserBasicInfoCriteria;
import com.cornergj.model.Entity.Value;
import com.cornergj.model.CarouselImg;
import com.cornergj.model.FrontImg;
import com.cornergj.model.ServiceContent;
import com.cornergj.model.SiteOfProvince;
import com.cornergj.model.ThirdAuthorizeUser;
import com.cornergj.model.UserBasicInfo;
import com.cornergj.response.ErrorCode;
import com.cornergj.response.JsonResult;
import com.cornergj.service.CommonUserService;
import com.cornergj.service.FrontImgService;
import com.cornergj.service.ServiceContentService;
import com.cornergj.service.ThirdAuthorizeUserService;
import com.cornergj.service.UserBasicInfoService;
import com.cornergj.uitl.ALiYunSmsUtil;
import com.cornergj.uitl.CryptUtil;
import com.cornergj.uitl.OKHttpUtil;
import com.cornergj.uitl.PropertyUtil;



/**
 * Title:
 * Model:
 * Description:
 * @author 郑耿杰
 * @date 2018年1月21日
 */
@Controller
@RequestMapping("/thirdauthorize")
public class TheThirdAuthorizeController {
	
	@Autowired
	private FrontImgService frontImgService;
	@Autowired
	private ServiceContentService serviceContentService;
	@Autowired
	private ThirdAuthorizeUserService thirdAuthorizeUserService;
	@Autowired
	private UserBasicInfoService userBasicInfoService;
	
	@RequestMapping(value="/getauthorizeurl",method= RequestMethod.GET)
	@ResponseBody
    public JsonResult getauthorize(HttpServletRequest request,HttpServletResponse response) {
		JsonResult result=new JsonResult();
		Oauth oauth = new Oauth();
		try {
			String authorizeurl=oauth.authorize("code");
			result.setData(authorizeurl);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.addErrorCode(ErrorCode.GET_THIRD_AUTHORIZE);
		}
		return result;
    }
	
	@RequestMapping(value = "/frontpage/toindex", method = RequestMethod.GET)
	public String turnToThird(HttpServletRequest request,String code) {
		if(code==null || "".equals(code)){
			getIndexContent(request);
			return "redirect:/frontpage/toindex.do";
		}else{
			String posturl=PropertyUtil.getProperty("accessTokenURL")+
					"code="+code+"&client_id="+PropertyUtil.getProperty("client_ID")+
					"&client_secret="+PropertyUtil.getProperty("client_SERCRET")+"&grant_type=authorization_code&redirect_uri="+
					PropertyUtil.getProperty("redirect_URI");
			String res=OKHttpUtil.httpPost(posturl, "");
			JSONObject jsonObject=new JSONObject(res);
			try{
				String access_token=(String) jsonObject.get("access_token");
				String uid=(String) jsonObject.get("uid");
				String getUserInfourl=PropertyUtil.getProperty("thirdUserInfoURL")+"access_token="+
						access_token+"&uid="+uid;
				String userInfoRes=OKHttpUtil.httpGet(getUserInfourl);
				JSONObject userJson=new JSONObject(userInfoRes);
				String username=(String)userJson.get("name");
				String avatarurl=(String)userJson.get("avatar_large");
				
				ThirdAuthorizeUserCriteria criteria =new ThirdAuthorizeUserCriteria();
				criteria.setUid(Value.eq(uid));
				ThirdAuthorizeUser getselectUser=thirdAuthorizeUserService.selectOne(criteria);
				if(getselectUser==null){//第一次登录
					ThirdAuthorizeUser thirdUser=new ThirdAuthorizeUser();
					thirdUser.setAccessToken(access_token);
					thirdUser.setUid(uid);
					thirdUser.setUsername(username);
					thirdUser.setAvatarImg(avatarurl);
					
					UserBasicInfo saveuserBasicInfo=new UserBasicInfo();
					saveuserBasicInfo.setHeadimgUrl(avatarurl);
					saveuserBasicInfo.setUsername(username);
					saveuserBasicInfo.setUserUuid(UUID.randomUUID().toString());
					saveuserBasicInfo.setIslock(0);
					int userid=userBasicInfoService.save(saveuserBasicInfo);
					
					thirdUser.setUserKey(userid);
					thirdAuthorizeUserService.save(thirdUser);
				}
				//登录
				ThirdAuthorizeUserCriteria criteria2 =new ThirdAuthorizeUserCriteria();
				criteria2.setUid(Value.eq(uid));
				ThirdAuthorizeUser thirdUser2=thirdAuthorizeUserService.selectOne(criteria2);
				
				UserBasicInfo getBasicInfo=userBasicInfoService.selectOne(thirdUser2.getUserKey());
				
				HttpSession session=request.getSession();
				session.setAttribute("COMMONUSER", getBasicInfo);
				
			}catch(Exception e){
				e.printStackTrace();
				getIndexContent(request);
				return "redirect:/frontpage/toindex.do";
			}
			getIndexContent(request);
			return "front/index";
		}
	}
	
	public void getIndexContent(HttpServletRequest request){
		FrontImgCriteria bgcriteria=new FrontImgCriteria();
		bgcriteria.setImgType(Value.eq(1));
		List<FrontImg> bglist=frontImgService.selectList(bgcriteria);
		FrontImgCriteria imgcriteria=new FrontImgCriteria();
		imgcriteria.setImgType(Value.eq(2));
		List<FrontImg> imglist=frontImgService.selectList(imgcriteria);
		/*
		 * 自定义类型，用于轮播传递
		 */
		List<CarouselImg> carousellist=new ArrayList<CarouselImg>();
		for(int i=0;i<bglist.size();i++){
			CarouselImg carouselImg=new CarouselImg();
			carouselImg.setBg_url(bglist.get(i).getImgUrl());
			carouselImg.setExplain(bglist.get(i).getImgDescribe());
			if(imglist.get(i).getForeignKey()==bglist.get(i).getId()){
				carouselImg.setImg_url(imglist.get(i).getImgUrl());
			}
			
			carousellist.add(carouselImg);
		}
		FrontImgCriteria goodnannycriteria=new FrontImgCriteria();
		goodnannycriteria.setImgType(Value.eq(3));
		List<FrontImg> goodnannylist=frontImgService.selectList(goodnannycriteria);
		
		List<ServiceContent> serviceContentlist=serviceContentService.selectAll();
		
		request.setAttribute("ServiceContentlist",serviceContentlist);
		request.setAttribute("GoodNannyList",goodnannylist);
		request.setAttribute("CarouselImgList",carousellist);
	}
	
}
